﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace EnviarMailDeArchivo
{
    public partial class Form1 : Form
    {
        List<String> Adjuntos = new List<string>();
        List<String> listaDeMails;
        String Correo = "";
        public Form1()
        {
            InitializeComponent();

            listaDeMails = new List<string>();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }



        private String EnviarCorreo(String username, String password, String to, string subject, string body, string server, int puerto, List<String> att)
        {
            System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();

            System.Net.NetworkCredential cred = new System.Net.NetworkCredential(username, password);

            mail.To.Add(to);
            mail.Subject = subject;

            mail.From = new System.Net.Mail.MailAddress(username);
            mail.IsBodyHtml = false;
            mail.Body = body;


            foreach (string s in Adjuntos)
            {
                mail.Attachments.Add(new System.Net.Mail.Attachment(s));
            }

            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(server);
            smtp.UseDefaultCredentials = false;
            smtp.EnableSsl = true;
            smtp.Credentials = cred;
            smtp.Port = puerto; //587
            try
            {
                smtp.Send(mail);
                return "Mensaje enviado exitosamente a " + to;
            }

            catch (Exception e)
            {
                return "Menasje no pudo ser enviado a " + to+"\n"+e.Message;
            }
            



        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "Archivo de Texto|*.txt";
            if (openFileDialog1.ShowDialog() == DialogResult.OK&&openFileDialog1.FileName.EndsWith(".txt"))
            {
                listaDeMails = new List<string>();
                char[] se = { '\\' };
                label2.Text = openFileDialog1.FileName.Split(se)[openFileDialog1.FileName.Split(se).Count()-1];
                char[] sep = { ',', ' ' };
                StreamReader sr = new StreamReader(openFileDialog1.FileName);
                String str = sr.ReadLine();
                sr.Close();

                listaDeMails = str.Split(sep, StringSplitOptions.RemoveEmptyEntries).ToList();
                listaDeMails.Sort();

                listBox1.Items.Clear();
                listBox1.Items.AddRange(listaDeMails.ToArray());

                MessageBox.Show("Ha cargado los contactos exitosamente");
            }

            else
            {
                MessageBox.Show("Los contactos no han sido cargados, seleccione un archivo valido");

            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            openFileDialog2.Filter = "Archivo de Texto|*.txt|Pagina web|*.html|Pagina Web|*.htm";
            if (openFileDialog2.ShowDialog() == DialogResult.OK && (openFileDialog2.FileName.EndsWith(".txt") || openFileDialog2.FileName.EndsWith(".html") || openFileDialog2.FileName.EndsWith(".htm")))
            {
                char[] se = { '\\' };
                StreamReader sr = new StreamReader(openFileDialog2.FileName);
                label4.Text = openFileDialog2.FileName.Split(se)[openFileDialog2.FileName.Split(se).Count()-1];

                while (true)
                {
                    String w = sr.ReadLine();
                    if (w != null)
                    {
                        Correo += w + "\r\n";
                    }
                    else
                    {
                        break;
                    }

                }

                sr.Close();

                MessageBox.Show("Mensaje Cargado Exitosamente");
            }
            else
            {
                MessageBox.Show("No se pudo cargar el correo");
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            log.Clear();
            if (listaDeMails.Count > 0 && From.Text != "" && Pass.Text != "" && Servidor.Text != "" && Puerto.Text != "" && Subject.Text != "")
            {
                foreach (String t in listaDeMails)
                {

                    try
                    {
                        log.Text += EnviarCorreo(From.Text, Pass.Text, t, Subject.Text, Correo, Servidor.Text, Int32.Parse(Puerto.Text), Adjuntos) + "\r\n";

                    }

                    catch
                    {

                    }


                }
                MessageBox.Show("Mensajes Enviados");

            }

            else
            {
                MessageBox.Show("No se han podido enviar los correos");
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            char[] sep = { '\\' };
            if (openFileDialog3.ShowDialog() == DialogResult.OK)
            {
                Adjuntos.Add(openFileDialog3.FileName);

               Adjunto.Items.Add(openFileDialog3.FileName.Split(sep)[openFileDialog3.FileName.Split(sep).Count()-1]);
            }
        }
    }
}
